package org.gwh.airagknowledge.core.document;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.gwh.airagknowledge.entity.Document;
import org.gwh.airagknowledge.entity.KnowledgeBase;
import org.gwh.airagknowledge.repository.DocumentRepository;
import org.gwh.airagknowledge.repository.KnowledgeBaseRepository;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

@Slf4j
@Component
@RequiredArgsConstructor
public class DocumentLoader {

    private final DocumentRepository documentRepository;
    private final KnowledgeBaseRepository knowledgeBaseRepository;
    private final DocumentProcessor documentProcessor;

    @Value("${file.upload.dir:./uploads}")
    private String uploadDir;

    public Document uploadDocument(MultipartFile file, Long knowledgeBaseId) throws IOException {
        // 获取知识库
        KnowledgeBase knowledgeBase = knowledgeBaseRepository.findById(knowledgeBaseId)
                .orElseThrow(() -> new IllegalArgumentException("Knowledge base not found with ID: " + knowledgeBaseId));
        
        // 创建上传目录
        Path uploadPath = Paths.get(uploadDir);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }
        
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename != null ? originalFilename.substring(originalFilename.lastIndexOf(".")) : "";
        String uniqueFilename = UUID.randomUUID() + fileExtension;
        
        // 保存文件
        Path filePath = uploadPath.resolve(uniqueFilename);
        Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
        
        // 创建文档记录
        Document document = Document.builder()
                .knowledgeBase(knowledgeBase)
                .fileName(originalFilename != null ? originalFilename : uniqueFilename)
                .fileType(file.getContentType())
                .fileSize(file.getSize())
                .filePath(filePath.toString())
                .status("PROCESSING")
                .build();
        
        // 保存文档记录
        Document savedDocument = documentRepository.save(document);
        
        // 启动异步处理
        documentProcessor.processDocumentAsync(savedDocument);
        
        return savedDocument;
    }
} 